import React, { useState } from "react";
import { List, ListItemButton, ListItemText, Collapse } from "@mui/material";
import { ExpandLess, ExpandMore } from "@mui/icons-material";
import { ALL_TYPES } from "./common";

export default function NestedList({ data, refs }) {
  const [openMap, setOpenMap] = useState({});
  const curLevelType = ALL_TYPES.find((type) => data[type]);
  const curLevelItems = data[curLevelType] || [];

  const handleClick = (event, item) => {
    event.stopPropagation();
    if (item.children.length > 0) {
      setOpenMap((prevOpenMap) => ({
        ...prevOpenMap,
        [item._id]: !prevOpenMap[item._id],
      }));
    }
  };

  const anchorPosition = (id) => {
    refs[id].current.scrollIntoView({ behavior: "smooth" });
  };

  return (
    <List component="div">
      {curLevelItems.map((item) => (
        <div key={item._id} style={{ paddingLeft: "1.5rem", width: "80%" }}>
          <ListItemButton onClick={() => anchorPosition(item._id)}>
            <ListItemText primary={item.title} />
            {item.children.length > 0 &&
              (openMap[item._id] ? (
                <ExpandLess onClick={(event) => handleClick(event, item)} />
              ) : (
                <ExpandMore onClick={(event) => handleClick(event, item)} />
              ))}
          </ListItemButton>
          <Collapse in={openMap[item._id]} timeout="auto" unmountOnExit>
            <NestedList data={item} refs={refs} />
          </Collapse>
        </div>
      ))}
    </List>
  );
}
